import React from 'react';
import Menu from '../Menu';
import Button from '../Form/Button';
import {createBrowserHistory} from 'history';


export const Route = () => (<React.Fragment />);

export default class DemoApplication extends React.Component {
    constructor(props) {
        super(props);
        this.History = createBrowserHistory();
        const list = this.getList(props);

        this.state = {
            listComponents: list,
            current: this.resolve(this.History.location.pathname, list) || list[0] || null
        };
        if(this.state.current.url !== this.History.location.pathname) {
            this.History.replace(this.state.current);
        }
        this.stopRouter = this.History.listen(location => this.setState({
            current: this.resolve(location.pathname)
        }));
    }
    resolve(path, list) {
        list = list || this.state.listComponents;
        return list.find(item => `/${item.url}` === path);
    }
    getList(props) {
        return React.Children.map(props.children, child => (child && {
            url: child.props.url,
            label: child.props.label,
            Component: child.props.Component
        }));
    }
    render() {
        const {listComponents, current} = this.state,
            baseClass = 'demo-app';
        return (<div className={baseClass}>
            <Menu
                className={baseClass+'__menu'}
                itemTag={iProps => {
                    return (<Button onClick={() => this.History.push(`/${iProps.to}`)}>
                        {iProps.children}
                    </Button>);
                }}
                list={listComponents.map(item => ({
                    to: item.url.toLowerCase(),
                    caption: item.label
                }))}
            />
            <div className={baseClass + 'content'} >
                {current && React.createElement(current.Component)}
            </div>
        </div>);
    }
}
